<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>键盘事件 keyCode 兼容性写法</title>
    </head>
    <body>
        <input type="text" id="inp" />
        <div id="result">点我</div>
        <script>
        var inp = document.getElementById('inp')
        var result = document.getElementById('result')

        function getKeyCode(e) {
          e = e ? e : (window.event ? window.event : "")
          return e.keyCode ? e.keyCode : e.which
        }

        inp.onkeypress = function(e) {
          result.innerHTML = getKeyCode(e)
        }
        inp.onkeyup = function(e) {
          result.style.backgroundColor="#ff0";
        }
        inp.onkeydown = function(e) {
          result.style.backgroundColor="#f00";
        }
        </script>
    </body>
</html>